package com.yytek.gw.service;

import com.alibaba.fastjson2.JSON;
import com.yytek.common.client.net.IotMqttClient;
import com.yytek.common.core.constant.Constants;
import com.yytek.common.core.domain.DeviceCache;
import com.yytek.common.core.domain.R;
import com.yytek.common.core.utils.bean.BeanCopyUtils;
import com.yytek.gw.converter.ScriptConverter;
import com.yytek.nmp.api.RemoteNmpService;

import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Map;

/**
 * 驱动统一消息处理业务
 */
@Service
public class DriverMsgCommonService {
    @Resource
    private RemoteNmpService remoteNmpService;
    @Resource
    public IotMqttClient iotMqttClient;

    /**
     * 统一处理各个网关接收信息解析后发送各个服务
     * @param deviceId 设备id
     * @param msg 消息
     */
    public void sendToCommonHandleMsg(String deviceId, Object msg) {
        R result = remoteNmpService.getDeviceCache(deviceId);
        if(result.getCode() == Constants.SUCCESS){
            if(result.getData() != null){
                //获取解析脚本
                DeviceCache deviceCache = BeanCopyUtils.mapToBean((Map<String, Object>) result.getData(),DeviceCache.class);
                String script =deviceCache.getDataAnalysisUp();
                //解析固定格式
                ScriptConverter scriptConverter = new ScriptConverter();
                scriptConverter.setScript(script);
                //获取各个topic数据
                Map<String,Object> topicData = scriptConverter.decode(msg);
                if(topicData != null){
                    //根据key发送到不同服务topic
                    for (Map.Entry entry : topicData.entrySet()) {
                        iotMqttClient.publish("/"+entry.getKey().toString(), JSON.toJSONString(entry.getValue()));
                    }
                }
            }
        }

    }

    /**
     * 统一脚本编码为发送消息
     *
     * @param deviceId
     * @param data
     * @return
     */
    public Object anaylisToMsg(String deviceId, Object data) {
        R result = remoteNmpService.getDeviceCache(deviceId);
        if(result.getCode() == Constants.SUCCESS) {
            //获取解析脚本
            DeviceCache deviceCache = BeanCopyUtils.mapToBean((Map<String, Object>)result.getData(), DeviceCache.class);
            String script = deviceCache.getDataAnalysisUp();
            //解析固定格式
            ScriptConverter scriptConverter = new ScriptConverter();
            scriptConverter.setScript(script);
            //编码返回对象
            return scriptConverter.encode(data, deviceCache);
        }else{
            return "";
        }
    }
}
